package com.itheima.health.controller;

import cn.hutool.core.util.IdUtil;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.AliOssUtil;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zhangmeng
 * @description 套餐控制器
 * @date 2019/9/26
 **/
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {
    @Resource
    private QiniuUtils qiniuUtils;

    @Resource
    private SetMealService setMealService;

    /**
     * 注入阿里云上传文件工具类
     */
    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 上传文件
     *
     * @param imgFile 上传的文件
     * @return {@link Result} 文件上传阿里云地址
     * @throws IOException ioexception
     */
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile imgFile) throws IOException {
        log.info("Uploading file {}", imgFile.getName());
        String newFileName = IdUtil.simpleUUID() + imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf("."));
        return new Result(Boolean.TRUE, MessageConst.PIC_UPLOAD_SUCCESS, aliOssUtil.upload(imgFile.getBytes(),newFileName));
    }

    /**
     * 添加套餐
     * @param setmeal   套餐基本信息
     * @param checkgroupIds 检查组ID列表
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal , Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}",setmeal,checkgroupIds);
        if(!StringUtils.isEmpty(setmeal.getImg())) {
            String img =setmeal.getImg().replace(qiniuUtils.getUrlPrefix(),"");
            setmeal.setImg(img);
        }
        //RPC调用添加数据
        setMealService.add(setmeal,checkgroupIds);
        return new Result(true,MessageConst.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean){
        //调用DAO层查询并返回
        PageResult pageResult = setMealService.findPage(queryPageBean);
        //构造返回结果并返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,pageResult);
    }
}
